<?php
include_once 'database/db.php';
include $_SERVER['DOCUMENT_ROOT']."/lib/spyc.php";
/**
 * 过期文件清理类
 */
class CleanFile
{
  private $DB;
  private $filepath;
  function __construct()
  {
    $this->DB = new DB();
    $ENV = spyc_load_file($_SERVER['DOCUMENT_ROOT'].'/properties/env.yml');
    $this->filepath=($ENV['upload']['path'])['0'];
  }

  public function start()
  {
    // 1. 查询出所有数据库中文件记录
    // 2. 对于每个文件判断是否过期
    // 3. 对过期文件进行删除并同时删除数据库记录
    $cursor = $this->DB->query('fileshare.files',['valid'=>true]);
    $deleteArray=[];
    foreach ($cursor as $document) {
      $id = $document->id;
      $ctime = $document->ctime;
      $fileName = $document->fileName;
      $filepath = $this->filepath.DIRECTORY_SEPARATOR.sha1($fileName);
      if ((time()-$ctime)>25*60*60) {
        // 循环删除文件
        @unlink($filepath.DIRECTORY_SEPARATOR. $fileName);
        // 删除文件夹
        @rmdir($filepath);
        $deleteArray[]=['id'=>$id];
      }
    }

    foreach ($deleteArray as $deleteItem) {

      $this->DB->delete('fileshare.files',$deleteItem);
    }
  }
}
